package u

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"strconv"
	"time"
)

const (
	RedisKey_UserToken = "ez.user.token"
)

func CreateUserTokenKeyForRedis(token string, field string) string {
	return fmt.Sprintf("%s:%s.%s", RedisKey_UserToken, token, field)
}

func SetUserIdToRedis(token string, id int64, expiration int64) {
	cmd := ez.DBRedis.Set(CreateUserTokenKeyForRedis(token, "id"), id, time.Duration(expiration)*time.Second)
	if cmd.Err() != nil {
		ez.LogToConsoleNoTrace(cmd.Err().Error())
	}
}

func GetUserIdFromRedis(token string) int64 {
	cmd := ez.DBRedis.Get(CreateUserTokenKeyForRedis(token, "id"))
	if cmd.Err() != nil {
		ez.LogToConsoleNoTrace(cmd.Err().Error())
		return 0
	}
	if cmd.Val() != "" {
		uid, _ := strconv.ParseInt(cmd.Val(), 10, 64)
		return uid
	}
	return 0
}

func SetUserRolesToRedis(token string, roles []int64, expiration int64) {
	ez.DBRedis.SAdd(CreateUserTokenKeyForRedis(token, "roles"), roles)
	ez.DBRedis.Expire(CreateUserTokenKeyForRedis(token, "roles"), time.Duration(expiration)*time.Second)
}

func GetUserRolesFromRedis(token string) []int64 {
	cmd := ez.DBRedis.SMembers(CreateUserTokenKeyForRedis(token, "roles"))
	if cmd.Err() != nil {
		ez.LogToConsoleNoTrace(cmd.Err().Error())
		return nil
	}
	if cmd.Val() != nil {
		roles := make([]int64, 0)
		for _, s := range cmd.Val() {

			id, _ := strconv.ParseInt(s, 10, 64)
			roles = append(roles, id)
		}
		return roles
	}
	return nil
}
